import { Upgrader } from "@/roles/upgrader.role";
import { Harvester } from "../roles/harvester.role";
import { Transporter } from "@/roles/transporter.role";
import { Builder } from "@/roles/builder.role";

// 角色管理系统
export class RoleManager {

  private static readonly roleConfigs: Record<RoleType, IRole> = {
    harvester: undefined,
    transporter: undefined,
    upgrader: undefined,
    builder: undefined,
    repairer: undefined,
    attacker: undefined
  };

  // 初始化注册所有角色
  static initialize() {
    this.registerRole('harvester', new Harvester());
    this.registerRole('transporter', new Transporter());
    this.registerRole('upgrader', new Upgrader());
    this.registerRole('builder', new Builder());
  }

  // 注册角色
  static registerRole(roleName: RoleType, role: IRole): boolean {
    const roleConfig = this.roleConfigs[roleName];

    if (roleConfig === undefined) {
      this.roleConfigs[roleName] = role;
      console.log(`✅ 注册角色 ${roleName} 成功`);
      return true;
    } else {
      console.log(`⚠️ 角色 ${roleName} 已注册，跳过重复注册`);
      return false;
    }
  }

  // 获取角色
  static getRole(roleName: RoleType): IRole {
    return this.roleConfigs[roleName] as IRole;
  }

  // 获取角色能耗
  static getRoleMinCost(roleName: RoleType): number {
    const role = this.getRole(roleName);

    if (!role) {
      console.log(`⚠️ getRoleMinCost: 角色 ${role} 不存在。`);
      return;
    }

    return role.minCost;
  }

  // 获取角色身体配置
  static getBodyForRole(roleName: RoleType): BodyPartConstant[] {
    const role = this.getRole(roleName);

    if (!role || role.bodyPart.length === 0) {
      console.log(`⚠️ getBodyForRole: 角色 ${role} 的 baseBody 配置无效，使用默认配置。`);
      return;
    }

    return role.bodyPart;
  }

  // 获取所有角色配置
  static getAllRoles(): IRole[] {
    return Object.values(this.roleConfigs).filter(Boolean) as IRole[];
  }

  // 获取所有角色
  static getAllRoleTypes(): RoleType[] {
    // 获取已注册的角色，过滤undefined
    const registerRoles = Object.entries(this.roleConfigs)
      .filter(([_, role]) => role !== undefined)
      .map(([roleType]) => roleType) as RoleType[];
    return registerRoles;
  }

  // 按照优先级由小到大进行排列
  static getRolePriority(): RoleType[] {
    // 获取所有已配置的角色，过滤undefined
    const configuredRoles = Object.values(this.roleConfigs)
      .filter(role => role !== undefined) as IRole[];

    // 按priority属性排序
    const sortedRoles = configuredRoles.sort((a, b) => a.priority - b.priority);

    // 提取排序后的roleType数组
    return sortedRoles.map(role => role.role);
  }
}